package me.info.sboot.app.service;

import java.io.IOException;
import java.util.List;

import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.json.JsonXContent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import io.vavr.control.Try;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import me.info.sboot.app.domain.News;
import me.info.sboot.app.holder.EsTemplate;

/**
 * @author Amber L
 * @version v0.0.1
 * @desc
 * @date 2020/12/25 16:51
 */
@Slf4j
@Service
public class NewsServiceImpl implements NewsService {

  private static final String INDEX_NAME = "demo.news";
  @Autowired EsTemplate esTemplate;

  @SneakyThrows
  @Override
  public boolean createIndex() {
    Try<XContentBuilder> mappings = Try.of(this::generateMapping);
    return esTemplate.createIndex(INDEX_NAME, mappings.get());
  }

  @Override
  public boolean saveAll(List<News> list) {
    try {
      return esTemplate.addBulk(INDEX_NAME, list);
    } catch (IOException e) {
      log.error(e.getMessage(), e);
    }
    return false;
  }

  @SneakyThrows
  @Override
  public boolean delIndex(String indexName) {
    return esTemplate.deleteIndex(indexName);
  }

  public XContentBuilder generateMapping() throws IOException {
    return JsonXContent.contentBuilder()
        .startObject()
        // .startObject("mappings")
        .startObject("properties")
        .startObject("id")
        .field("type", "long")
        .field("index", "true")
        .endObject()
        .startObject("title")
        .field("type", "text")
        .field("analyzer", "ik_max_word")
        .endObject()
        .startObject("tag")
        .field("type", "text")
        .field("analyzer", "ik_max_word")
        .endObject()
        .startObject("content")
        .field("type", "text")
        .field("index", "true")
        .field("analyzer", "ik_max_word")
        .endObject()
        .startObject("uniqueId")
        .field("type", "keyword")
        .field("index", "false")
        .endObject()
        .startObject("publishTime")
        .field("type", "date")
        .field("format", "strict_date_optional_time||epoch_millis")
        .endObject()
        .startObject("created")
        .field("type", "date")
        .field("format", "strict_date_optional_time||epoch_millis")
        .endObject()
        .endObject()
        .endObject();
  }
}
